package com.catmiao.ai.controller;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;

@RestController
@Slf4j
public class ChatController {

    @Autowired
    private ChatModel chatModel;

    @Value("classpath:static/a.jpg")
    private Resource resource;


    @GetMapping("/image/call")
    public String readImageContent() throws Exception {

        String result = null;

        // 1. 图片转码：通过Base64编码将图片转化为字符串

        Base64.Encoder encoder = Base64.getEncoder();
        String imageContent = encoder.encodeToString(resource.getContentAsByteArray());

        // 2. 提示词指定：结合ImageContent和TextContent一起发送到模型进行处理\
        UserMessage userMessage = UserMessage.from(
                TextContent.from("解释下图片中描述的什么"),
                ImageContent.from(imageContent, "image/jpg")
        );

        // 3. API调用：使用 OpenAIChatModel 来构建请求，并通过 chat() 方法调用模型
        ChatResponse response = chatModel.chat(userMessage);

        //  文本提示和图片


        // 4. 解析与输出，获取大模型的回复，打印出处理后的结果
        result = response.aiMessage().text();

        log.info("result: {}", result);

        return result;
    }

}